// array indexes for the _signal arrays
const int GREEN = 0;
const int YELLOW = 1;
const int RED = 2;

// arduino pin numbers for each LED: green, yellow, red
int north_south_signal[3] = {5, 6, 7};
int east_west_signal[3] = {8, 9, 10};

// array indexes used for the signal_states array
const int NORTH_SOUTH = 0;
const int EAST_WEST = 1;

// this holds all the possible light combinations
// first column is the north/south signal, second is the east/west signal
int signal_states[6][2] = {
  {GREEN,RED},
  {YELLOW,RED},
  {RED,RED},
  {RED,GREEN},
  {RED,YELLOW},
  {RED,RED}
};

// start at the last state so it will loop back to the beginning
volatile int current_state = 5;

// change intervals in seconds
int Min_Green = 9;
int Yellow_Change = 3;
int Red_Clear = 1;


void next_state() {
  // this will count from 0 to 5 and then loop around to 0 again (% = modulus operator)
  int new_state = (current_state+1) % 6;
  
  // figure out which light is currently lit on the N/S signal, and which one needs to be lit next
  int current_north_south = signal_states[current_state][NORTH_SOUTH];
  int new_north_south = signal_states[new_state][NORTH_SOUTH];
  
  // if they aren't equal, the N/S light needs to change
  if (current_north_south != new_north_south) {
    digitalWrite(north_south_signal[current_north_south], LOW);
    digitalWrite(north_south_signal[new_north_south], HIGH);
  }
  
  
  // this is identical to the section above, just using the E/W signal
  int current_east_west = signal_states[current_state][EAST_WEST];
  int new_east_west = signal_states[new_state][EAST_WEST];
  
  if (current_east_west != new_east_west) {
    digitalWrite(east_west_signal[current_east_west], LOW);
    digitalWrite(east_west_signal[new_east_west], HIGH);
  }

  // after we've changed all the lights, update the current state
  current_state = new_state;
}


void setup() {
  noInterrupts();

  pinMode(north_south_signal[GREEN], OUTPUT);
  pinMode(north_south_signal[YELLOW], OUTPUT);
  pinMode(north_south_signal[RED], OUTPUT);
  
  pinMode(east_west_signal[GREEN], OUTPUT);
  pinMode(east_west_signal[YELLOW], OUTPUT);
  pinMode(east_west_signal[RED], OUTPUT);
  
  interrupts();
  next_state();  
}


void loop() {
  // the loop simulates the timer. I think this could be empty once we get the interrupts working.
  delay(Min_Green*1000);
  next_state();
  delay(Yellow_Change*1000);
  next_state();
  delay(Red_Clear*1000);
  next_state();  
}





